<template>
  <div>
    <el-table-form ref="form" :model="query">
      <el-form-item label="统计日期" prop="date" :table-form-merge="1.1">
        <el-date-picker
          v-model="query.date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
        />
      </el-form-item>

      <el-form-item label="所属机构" prop="query">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
        />
      </el-form-item>

      <template v-slot:btns>
        <el-button
          v-permission="1"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
        <el-button
          v-permission="2"
          type="primary"
          icon="el-icon-download"
          @click="tryPrint"
        >导出</el-button>
      </template>
    </el-table-form>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      class="table"
      border
      :row-key="setRowKey"
      highlight-current-row
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      element-loading-text="加载中"
      :column="column"
      :data="treeTableData"
      custom-column
      @fetch="fetchData"
    />
  </div>
</template>

<script>
  import { goodsExchangeStatisticsList, queryMap } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  export default {
    name: 'goodsExchangeStatistics',
    data() {
      return {
        query: {
          orgSNNo: '',
          date: []
        },
        // tableData: [],
        treeData: [],
        column: [],
        treeTableData: []
      }
    },
    computed: {
      ...mapGetters(['orgList'])
    },
    created() {
      // this.queryOptionsMap();
      this.getTreeData()
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1] = await Promise.all([
          queryMap({ enumName: 'OrderSource' })
        // queryMap({ enumName: 'CustomerType' })
        ])

        this.orderSourceOptions = res1.data
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      setRowKey(row) {
        return `${row.id}-${row._parentId}`
      },
      initData(data) {
        const map = {}
        const columns = [{ label: '统计日期', prop: 'name' }]
        const tempdatas = []
        let curitem,
            curparent
        const footer = {
          id: '0',
          name: '合计'
        }
        let k = 1
        let key = 'x' + k
        data.forEach((item) => {
          if (!map[item.GoodsName]) {
            k++
            key = 'x' + k
            columns.push({ label: item.GoodsName, prop: key, width: 150 })
            map[item.GoodsName] = key
          } else {
            key = map[item.GoodsName]
          }
          if (!curitem || curitem.id !== item.OrgId || curparent.id !== item.parentId) {
            curitem = undefined
            curitem = {}
            tempdatas.push(curitem)
          }
          curitem._parentId = item.parentId

          if (!curparent || curparent.id !== item.parentId) {
            curparent = undefined
            curparent = { id: item.parentId, name: item.parentName }
            tempdatas.push(curparent)
          }
          curitem.id = item.OrgId
          curitem.name = item.OrgName
          curitem[key] = item.count
          if (curparent[key]) {
            curparent[key] += curitem[key]
          } else {
            curparent[key] = curitem[key]
          }

          // 汇总
          if (footer[key]) {
            footer[key] += curitem[key]
          } else {
            footer[key] = curitem[key]
          }
        })

        this.treeTableData = getTreeData(tempdatas, '_parentId', 'id')
        this.column = columns
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        // if (this.date && this.date.length === 2) {
        //   query[this.dateType] = moment(this.date[0]).format();
        //   query[`${this.dateType}End`] = moment(this.date[1]).format();
        // }
        const res = await goodsExchangeStatisticsList(query)
        if (res.status === 200) this.initData(res.data || [])
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      tryPrint() {}
    }
  }
</script>

<style lang="scss" scoped></style>
